# _*_ coding : utf-8 _*_
# @Time : 2023/12/5 19:43
# @Author : 韩宗森
# @File : 10_ajax的get请求豆瓣电源前10页数据
# @Project : pythonProject

# 下载豆瓣电影前10页的数据
# (1)请求对象的定制
# (2)获取响应的数据
# (3)下载数据

import urllib.parse
import urllib.request


# (1)请求对象的定制
def create_request(page):
    base_url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&'

    data = {
        'start': (page - 1) * 20,
        'limit': 20
    }
    data = urllib.parse.urlencode(data)

    url = base_url + data

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }

    # (1)请求对象的定制
    request = urllib.request.Request(url=url, headers=headers)

    return request


# (2)获取响应的数据
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


# (3)数据下载到本地
def down_load(page, content):
    with open('豆瓣_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        fp.write(content)


# 程序入口
if __name__ == '__main__':
    start_page = 1  # int(input('请输入开始页码'))
    end_page = 10  # int(input('请输入结束页码'))

    for page in range(start_page, end_page + 1):
        # 每一页都有自己的请求对象的定制
        request = create_request(page)
        # (2) 获取响应的数据
        content = get_content(request)
        # (3)数据下载到本地
        down_load(page, content)
